 
package com.edu.hre.common.cache;

import java.util.Calendar;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
 
 
public class PassiveDynaHashTableCache implements PassiveDynaCache{

	private Logger logger = Logger.getLogger(PassiveDynaHashTableCache.class);
	
	private Hashtable items = new Hashtable(); 
	private int cacheSize = 500; //default

	 
	public PassiveDynaHashTableCache() { 
		this(500);
	}

	 
	public PassiveDynaHashTableCache(int _cacheSize) {
		cacheSize = _cacheSize; 
	}
	 
	public int getCacheSize() {
		return cacheSize;
	}

	/**
	 * @param i
	 */
	public void setCacheSize(int i) {
		cacheSize = i;
	}
	 
	public boolean containsKey(Object key){
		return items.containsKey(key);
	}
	 
	public void removeCachedItem(Object key) {
		if(items.containsKey(key))
			items.remove(key);
	}

	public void removeIfKeyStartWith(String startValue) {
		try {
			Enumeration e = items.keys();
			while(e.hasMoreElements()){
				Object k = e.nextElement();
				if(k instanceof String && ((String) k).startsWith(startValue)){
					removeCachedItem(k);
				}
			}
		} catch (Exception e) {
		}
	}

	public  Object getCachedItem(Object key) {
		try {
			Enumeration e = items.keys();
			while(e.hasMoreElements()){
				Object k = e.nextElement();
				CachedItem c = (CachedItem) items.get(k);
				if((c.getLastUpdatedTime() + c.getTimeToLive()) < System.currentTimeMillis()){
					// cache out of date
					removeCachedItem(k);
				}
			}
		} catch (Exception e) {
		}
		
		try {
			if(items.containsKey(key)){// in cache
				CachedItem cached = (CachedItem)items.get(key);
				return cached.getItem();
			} else{ 
				return null;
			}
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	
	public  void setCachedItem(Object key, int timeToLive ,Object value) {
		try {
			if(items.size() > cacheSize){ 
				Enumeration e = items.keys();
				Object eldestKey = e.nextElement();
				long eldestAge = ((CachedItem)items.get(eldestKey)).getLastUpdatedTime();
				while(e.hasMoreElements()){
					Object k = e.nextElement();
					CachedItem c = (CachedItem) items.get(k);
					if(eldestAge > c.getLastUpdatedTime()){// found elder
						eldestKey = k;
						eldestAge = c.getLastUpdatedTime();
					}
				}
				items.remove(eldestKey); 
			} 
			items.put(key, new CachedItem(value, timeToLive*1000 ,System.currentTimeMillis()));
		} catch (Exception e) { 
		}
	} 
	 
	public void clearCache() {
		items.clear();
	} 
}
